//彩宝新增和编辑页面

var RATE=Number($.cookie("GemRate")) || 1;
var EDITMODE=false;
var xhrVideo = new XMLHttpRequest();
(function(){
	var addForm={
		init:function(){
			myApp.showIndicator();
			this.bindEvents();
			this.loadCommon();
			myApp.hideIndicator();
		},
		bindEvents:function(){
			var self=this;
			$("#rate").text(RATE);
			//编辑
			args = GetUrlParms();				
			if(args["ID"]!=undefined){						
				ID = args["ID"];//产品ID		
				EDITMODE=true;
			}
			if(EDITMODE){
				$(".category").hide();
				self.bindData(ID);
				$("#page_title").html(_("彩宝编辑"));
			}else{
				$(".category").show();
				$("#page_title").html(_("彩宝新增"));
			}
			//切换主石类型
			self.changType(1);
			//self.sizeParams(1);
			$("#data_category").on("click","span",function(){
				$(this).addClass("active").siblings().removeClass("active");
				var type=$("#data_category span.active").attr("data-value");				
				self.changType(type);
			});
			//关闭弹框
			$("#close_tip_btn").on("click",function(){
				$("#tip_box").hide();
			});
			//美金与人民币的转换
			$('#rmb_per_input').bind('input propertychange', function() {
				var val=$(this).val();
				var weight=$("#Weight").val();
				if(weight=="" || weight<=0){
					myApp.alert(_("请先填重量"));
				}else{
					$("#usd_per_input").val((val/RATE).toFixed(2));
					$("#rmb_input").val((val*weight));
					$("#usd_input").val(((val/RATE)*weight).toFixed(2));
				}				
			});
			$('#usd_per_input').bind('input propertychange', function() {
				var val=$(this).val();
				var weight=$("#Weight").val();				
				if(weight=="" || weight<=0){
					myApp.alert(_("请先填重量"));
				}else{
					$("#rmb_per_input").val((val*RATE).toFixed(2));
					$("#rmb_input").val(((val*RATE)*weight).toFixed(2));
					$("#usd_input").val(((val)*weight).toFixed(2));
				}
				
			});
			$('#rmb_input').bind('input propertychange', function() {
				var val=$(this).val();
				var weight=$("#Weight").val();
				if(weight=="" || weight<=0){
					myApp.alert(_("请先填重量"));
				}else{
					var per_price=val/weight;
					$("#rmb_per_input").val(per_price.toFixed(2));	
					$("#usd_per_input").val((per_price/RATE).toFixed(2));	
					$("#usd_input").val((val/RATE).toFixed(2));
				}
				
			});
			$('#usd_input').bind('input propertychange', function() {
				var val=$(this).val();
				var weight=$("#Weight").val();
				if(weight=="" || weight<=0){
					myApp.alert(_("请先填重量"));
				}else{
					var per_price=val/weight;
					$("#usd_per_input").val(per_price.toFixed(2));	
					$("#rmb_per_input").val((per_price*RATE).toFixed(2));	
					$("#rmb_input").val((val*RATE).toFixed(2));
				}
				
			});
			
			//提交验证
			$("#submit_btn").on("click",function(){
				$("#form_data").submit();
			});
			$("#reset_btn").on("click",function(){
				if(EDITMODE){
					myApp.alert(_("编辑时不能重置参数！"));
				}else{
					$("#form_data")[0].reset();
				}				
			});
            var aValidate = $("#form_data").validate({
                debug: true, //调试模式取消submit的默认提交功能   
                focusInvalid: false, //当为false时，验证无效时，没有焦点响应  
                onkeyup: false,
                submitHandler: function (form) {   //表单提交句柄,为一回调函数，带一个参数：form
                    self.unImg();
                },
                rules: {
                    OriginSN: "required",
                    Weight: "required",
                    Color:"required",
                    Shape:"required",
                    Place:"required",
                    Status:"required",
                    Price: {
					    required: true,
					    max: 1000000000
					  },
					PriceCarat:{
						required: true,
					    max: 1000000000
					}
                },
                messages: {
                    OriginSN: "",
                    Weight: "",
                    Color:"",
                    Shape:"",
                    Place:"",
                    Status:"",
                    Price: {
                    	required:"",
					    max: _("价格必须小于9位数")
					}, 
					PriceCarat:{
						required:"",
						max: _("价格必须小于9位数")
					}
                }
            });
			
		},
		//编辑时绑定数据
		bindData:function(ID){
		    myApp.showIndicator();//显示加载中
			var self=this;
			var submitJson={};
			submitJson.ID=ID;
            submitJson.GoodsType=4;
			if(EDITMODE){
				submitJson.IsMyStock=true;
			}
			$.ajax({
				url:'/Team/GetProductData',
				type:'POST',
				data: JSON.stringify(submitJson),
				dataType:'JSON',
				contentType: "application/json; charset=utf8",
				success:function(result){
					var res=eval('(' + result + ')')
					if(res.msgcode==true){
                        var datas=res.msginfo.rows;
                        var data =datas[0];
						self.changType(data.Category);					
						$("#data_category").find("span").eq(data.Category-1).addClass("active").siblings().removeClass("active");//类型的绑定
						$("#form_data").setForm(data);//绑数据
						$("#usd_input").val(((data.Price)/RATE).toFixed(2));
						$("#usd_per_input").val(((data.PriceCarat)/RATE).toFixed(2))
						$("#id_input").prop({"name":"ID","value":data.ID});//ID

                        if(data.ShipTime){
                            $("#data_ShipTime").val($.trim(YearDateFormats(data.ShipTime)));
                        }
                        if(data.PurchaseTime){
                            $("#data_PurchaseTime").val($.trim(YearDateFormats(data.PurchaseTime)));//-买入时间
                        }
                        if(data.ArrivalTime){
                            $("#data_ArrivalTime").val($.trim(YearDateFormats(data.ArrivalTime)));//到货时间
                        }

                        //视频绑定
                        if(data.Videos!=''){
                            var _CRE_FILE = document.createElement("input");
                            _CRE_FILE.setAttribute("type", "file");
                            _CRE_FILE.setAttribute("class", "video_file");
                            _CRE_FILE.setAttribute("id", "video_input");
                            _CRE_FILE.setAttribute("style", "display:none");
                            _CRE_FILE.setAttribute("data-url",data.Videos );
                            $('.video_one').after(_CRE_FILE);
                            var videoHtml= '<section class="up-section fl close_f" style="margin-left: 5px; position: relative;">'+
                                '<span class="up-span"></span>'+
                                '<img src="/images/a7.png" class="close-upimg" onclick="closeVideo()">'+
                                '<img src="/images/video2.png" style="width: 100%;height: 100%;display: block;">'+
                                '</section>';
                            $('.video_one').after(videoHtml)
                        }


                        //图片的绑定
						if(data.Images!=""){
							imgs = data.Images.split("|");
							 for (var i=0; i< imgs.length;i++) {
							 	var img_boxHmtl=[
					    			'<section class="up-section fl load">',
										'<span class="up-span"></span>',
										'<img src="/images/a7.png" class="close-upimg">',
										'<img src=',imgs[i],' class="up-img" data-src=',imgs[i],'>',
										'<p class="img-namep"></p>',
										'<input id="taglocation" name="taglocation" value="" type="hidden">',
										'<input id="tags" name="tags" value="" type="hidden">',
									'</section>'
					    		].join('');
					    		$("#img_box").append(img_boxHmtl);
							 }
						}						
					}else{
						myApp.alert(_("加载失败！"));
					}
					myApp.hideIndicator();//隐藏加载中
				}
			});
		},

        dataURLtoBlob:function(dataurl) {
            var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1],
                bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
            while(n--){
                u8arr[n] = bstr.charCodeAt(n);
            }
            return new Blob([u8arr], {type:mime});
        },
        unImg:function() {
            var self=this;
            var len=$('.up-img').length;
            var formData=new FormData();
            for (var i=0;i<len;i++){
                var dataSrc=$('.up-img').eq(i).attr('data-src');
                if(dataSrc.indexOf('http://')==-1){
                    var blob= self.dataURLtoBlob(dataSrc);
                    formData.append("image", blob, "image" + i + ".png");
                }
            }
            $.ajax({
                url: "/team/UploadImage?type=gems",
                data: formData,
                type: 'POST',
                cache: false,
                processData: false,
                contentType: false,
                dataType: 'JSON',
                success: function(result) {
                    var _result=eval('('+result+')');

                    if(_result.result==true){
                        for(var i = 0; i < _result.successes.length; i++) {
                            $('.new_up').eq(i).attr('data-src', _result.successes[i][1]);
                        }
                    }
                    if($('.video_file').length>0){
                        self.HandVideoStr()
                    }else {
                        self.addProduct();
                    }
                },
                error:function(XMLHttpRequest, textStatus, errorThrown){
                    myApp.alert(XMLHttpRequest.responseText);
                }

            });
        },

        //上传视频 start
        HandVideoStr:function() {
            var self=this;
            var fd = new FormData();
            var _this=document.getElementById("video_input");

            if($('#video_input').attr('data-url')){
                self.addProduct($('#video_input').attr('data-url'))
            }else {
                fd.append("fileToUpload", _this.files[0]);
                xhrVideo.onreadystatechange = function() {
                    self.videoFun();
                };
                xhrVideo.open("post", 'UploadVideo?type=gems', true);
                xhrVideo.send(fd);
            }

        },
        videoFun:function() {
            var self=this;
            var mp4Data='';

            if(xhrVideo.readyState == 4 && xhrVideo.status == 200) {
                var obj = $.parseJSON(xhrVideo.responseText);
                var _result = eval('(' + obj + ')'); //eval()解析单个json对象
                if(_result.msgcode == false) {
                    myApp.alert(_result.msginfo);
                } else {
                    if(_result.result==false){
                        self.addProduct(mp4Data)
                    }else {

                        mp4Data=_result.successes[0][1];
                        self.addProduct(mp4Data)
                    }
                }
            }
        },
        //上传视频end

        //新增提交
		addProduct:function(mp4Data){
			//图片链接
			var images=[];
			var img_sectionLength=$(".img-section").find("section.up-section").length;
			if(img_sectionLength==0){
				myApp.alert(_("请上传图片"));
			}else{
				myApp.showPreloader(_("上传中，请稍等!"));
				//获取图片地址
				for(var i=0;i<img_sectionLength;i++){
					var img_li=$(".img-section").find("section.up-section").eq(i);
					var img_src=img_li.find(".up-img").attr("data-src");
					images.push(img_src);
				}
	    		var imgs=images.join('|');//拼成字符串
	    		$("#Images").val(imgs);//图片
	    		$("#Category").val($("#data_category span.active").attr("data-value"));
				// var params = $("#form_data").serializeArray();
			    var finalRes = $('#form_data').serializeArray().reduce(function(result, item){
		             result[item.name] = item.value;
		            return result;
		        }, {})//把提交的数据转为JSON格式
		        if(EDITMODE){
                    finalRes.GoodsType=4;
		        	var manageURL="/Team/ModifyProductData";
		        }else{
                    finalRes.GoodsType=4;
		        	var manageURL="/Team/AddProductData";
		        }
                finalRes.Videos=mp4Data||'';//视频
				 $.ajax({
				 	type:"POST",
				 	url:manageURL,
				 	data:JSON.stringify(finalRes),
				 	contentType: "application/json; charset=utf-8",
	                success: function (result) {
	                	var _result = eval('(' + result + ')');//eval()解析单个json对象
	                	myApp.hidePreloader();
	                	if(EDITMODE){
	                		var tipString=_("修改");
	                	}else{
	                		var tipString=_("新增");
	                	}
	                	if(_result.result==true){
	                		myApp.alert(tipString+_("成功！"));
	                	}else{
	                		myApp.alert(tipString+_("失败！"));
	                	}
	                }
				 });
			}
			
		},
		
		//公共参数
		loadCommon:function(){
			//主石
			var category='';
			for (var i = 1; i < gem_category.length; i++) {
				if(i==1){
					category += '<span data-value="'+i+'" class="active">'+_(gem_category[i])+'</span>'
				}else{
					category += '<span data-value="'+i+'">'+_(gem_category[i])+'</span>'
				}				
			}
			
			$("#data_category").html(category);//主石类型
			//形状
			var shape='';
			for (var i = 0; i < gem[1].Shape.length; i++) {
				shape +='<option value="'+gem[1].Shape[i][0]+'">'+ _(gem[1].Shape[i][1]) +'</option>';
			}
			$("#data_shape").html(shape);
			//切工
			var cut='';
			for (var i = 0; i < gem[1].Cut.length; i++) {
				cut +='<option value="'+gem[1].Cut[i][0]+'">'+ _(gem[1].Cut[i][1]) +'</option>';
			}
			$("#data_cut").html(cut);
			//切工方式
			var cutmethod='';
			for (var i = 0; i < gem[1].CutMethod.length; i++) {
				cutmethod +='<option value="'+gem[1].CutMethod[i][0]+'">'+ _(gem[1].CutMethod[i][1]) +'</option>';
			}
			$("#data_cutmethod").html(cutmethod);
			//证书类型
			var cert='';
			for (var i = 0; i < gem[1].CertType.length; i++) {
				cert +='<option value="'+gem[1].CertType[i][0]+'">'+ _(gem[1].CertType[i][1]) +'</option>';
			}
			$("#data_cert").html(cert);
			//状态
			var status='';
			for(var i=0;i<gem[1].Status.length;i++){
				status+='<option value="'+gem[1].Status[i][0]+'">'+_(gem[1].Status[i][1])+'</option>';
			}
			$("#data_status").html(status);

			//付款
			var recStatus='';
            for(var i=0;i<gem[1].ReceiptStatus.length;i++){
                recStatus+='<option value="'+gem[1].ReceiptStatus[i][0]+'">'+_(gem[1].ReceiptStatus[i][1])+'</option>';
            }
            $("#data_recStatus").html(recStatus);


		},
		// 切换类型
		changType:function(type){
			$("#data_process,#data_oiliness").remove();
			if(type){
				//颜色
				var color='';
				for (var i = 0; i < gem[type].Color.length; i++) {
					color +='<option value="'+gem[type].Color[i][0]+'">'+ _(gem[type].Color[i][1]) +'</option>';
				}
				$("#data_color").html(color);
				//产地
				var place='';
				for (var i = 0; i < gem[type].Place.length; i++) {
					place +='<option value="'+gem[type].Place[i][0]+'">'+ _(gem[type].Place[i][1]) +'</option>';
				}
				$("#data_place").html(place);
				if(type==1 || type==2){
					//处理
					var process='<div class="form_control" id="data_process"><label>'+_("处理")+'：</label><select name="Process">';
					for(var i=0;i<gem[type].Process.length;i++){
						process+='<option value="'+gem[type].Process[i][0]+'">'+_(gem[type].Process[i][1])+'</option>'
					}
					process+='</select></div>';
					$("#data_color_box").after(process);
				}
				if(type==3){
					//油性
					var oiliness='<div class="form_control" id="data_oiliness"><label>'+_("油性")+'：</label><select name="Oiliness">';
					for(var i=0;i<gem[type].Oiliness.length;i++){
						oiliness+='<option value="'+gem[type].Oiliness[i][0]+'">'+_(gem[type].Oiliness[i][1])+'</option>'
					}
					oiliness+='</select></div>';
					$("#data_color_box").after(oiliness);
				}
			}
			
		},
	}
	addForm.init();
})();
